package com.tongyi.lizhishop.activitys;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.tongyi.lizhishop.managers.APIServiceManager;
import com.wuhenzhizao.titlebar.widget.CommonTitleBar;

import com.tongyi.lizhishop.R;
import com.tongyi.lizhishop.api.UserApi;
import com.tongyi.lizhishop.beans.CommonResonseBean;
import com.tongyi.lizhishop.common.BaseActivity;
import com.tongyi.lizhishop.common.CommonObserver;
import com.tongyi.lizhishop.views.shinkbutton.ShrinkButton;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class FindPasswordActivity extends BaseActivity {

    public static final int timeCount = 60 * 1000;
    @BindView(R.id.titlebar)
    CommonTitleBar titlebar;
    @BindView(R.id.activity_get_password)
    LinearLayout activityGetPassword;
    @BindView(R.id.leftTopTv)
    TextView leftTopTv;
    @BindView(R.id.centerTopEt)
    EditText centerTopEt;
    @BindView(R.id.rightTopTv)
    TextView rightTopTv;
    @BindView(R.id.leftSecondTv)
    TextView leftSecondTv;
    @BindView(R.id.centerSencondEt)
    EditText centerSencondEt;
    @BindView(R.id.rightSecondTv)
    TextView rightSecondTv;
    @BindView(R.id.leftThreeTv)
    TextView leftThreeTv;
    @BindView(R.id.centerThreeEt)
    EditText centerThreeEt;
    @BindView(R.id.rightThreeTv)
    TextView rightThreeTv;
    @BindView(R.id.confirm)
    ShrinkButton confirm;
    private String iphoneNum;
    private String centerTopEtText;
    private String centerSencondEtText;
    private String centerThreeEtText;
    private int width = 0;
    protected  String codeType="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_get_password);
        ButterKnife.bind(this);
        initTitleBarView(titlebar, "忘记密码");
        initView();
    }

    private void initView() {
        //监听三个edittext;
        centerTopEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                centerTopEtText = s.toString();
                checkBtnCanEnable();
            }

        });
        //监听三个edittext;
        centerSencondEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                centerSencondEtText = s.toString();
                checkBtnCanEnable();
            }

        });       //监听三个edittext;
        centerThreeEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                centerThreeEtText = s.toString();
                checkBtnCanEnable();
            }

        });

    }

    private void checkBtnCanEnable() {
        if (!TextUtils.isEmpty(centerTopEtText) && !TextUtils.isEmpty(centerSencondEtText) && !TextUtils.isEmpty(centerThreeEtText)) {
            confirm.setEnabled(true);
        } else {

            confirm.setEnabled(false);
        }

    }


    @OnClick({R.id.rightTopTv, R.id.rightSecondTv, R.id.confirm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rightTopTv:
                iphoneNum = centerTopEt.getText().toString();
                fixbug(rightTopTv);
                if (!RegexUtils.isMobileExact(iphoneNum)) {
                    ToastUtils.showShort("你输入的不是一个手机号!");
                    return;
                }

                rightTopTv.setEnabled(false);
                rightTopTv.setText("发送中...");
                codeType= "2";
                requestCode(rightTopTv);

                break;
            case R.id.rightSecondTv:
                iphoneNum = centerSencondEt.getText().toString();
                fixbug(rightSecondTv);
                if (!RegexUtils.isMobileExact(iphoneNum)) {
                    ToastUtils.showShort("你输入的不是一个手机号!");
                    return;
                }

                rightSecondTv.setEnabled(false);
                rightSecondTv.setText("发送中...");
                codeType="3";
                requestCode(rightSecondTv);

                break;
            case R.id.confirm:
                submitData();
                break;
        }
    }

    /**
     * 修复textview动态设置文字导致width变化的问题
     */
    private void fixbug(TextView tv) {
        if (width == 0) {
            width = tv.getWidth();
            ViewGroup.LayoutParams layoutParams = tv.getLayoutParams();
            layoutParams.width = width;
            tv.setLayoutParams(layoutParams);
        }
    }

    protected void submitData() {
        APIServiceManager.getInstance().create(UserApi.class)
                .changePassword(iphoneNum, centerThreeEt.getText().toString(), centerSencondEt.getText().toString())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<CommonResonseBean>() {
                    @Override
                    public void accept(CommonResonseBean commonResonseBean) throws Exception {
                        if ("succ".equals(commonResonseBean.getRe())) {
                            ToastUtils.showShort("修改密码成功,请登录");
                            finish();
                        } else if ("differ".equals(commonResonseBean.getRe())) {
                            ToastUtils.showShort("你输入的验证码不正确");
                            centerSencondEt.setText("");
                        } else {
                            ToastUtils.showShort("修改密码失败");
                        }
                        confirm.reset();


                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        ToastUtils.showShort("修改密码失败");
                        confirm.reset();
                    }
                });

    }

    private void requestCode(final TextView tv) {
        APIServiceManager.getInstance().create(UserApi.class)
                .getcode(iphoneNum, "2")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new CommonObserver<CommonResonseBean>() {
                    @Override
                    public void onSuccess(CommonResonseBean value) {
                        if ("succ".equals(value.getRe())) {
                            //验证码发送成功
                            beginCountDown(tv);
                        } else {
                            onFailure(null);
                        }
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        ToastUtils.showShort("请求失败,请重试");
                        tv.setText("请重试");
                    }
                });


    }

    private void beginCountDown(final TextView tv) {
        tv.setBackgroundColor(getResources().getColor(R.color.btn_disenable_color));
        CountDownTimer countDownTimer = new CountDownTimer(timeCount, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                int i = (int) (millisUntilFinished + 500) / 1000;
                tv.setText(i + "s");
            }

            @Override
            public void onFinish() {
                tv.setText("重新获取");
                tv.setBackgroundColor(getResources().getColor(R.color.mainColor));
                tv.setEnabled(true);
            }
        }.start();
    }
}
